using System.IO;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;

namespace DA.AnimGraph.Editor {
    
    /// 打开后操作见<see cref="AGEPreview"/>
    [AGTool("Preview", "打开预览场景")]
    public class Tool_Preview :  IAGTool {
        public void Execute(AGEContext ageContext) {
            string sceneName = "AGEPreviewScene";
            string scenePath = FindScenePath(sceneName);

            if (string.IsNullOrEmpty(scenePath))
            {
                Debug.LogError($"Scene '{sceneName}' not found in the project.");
                return;
            }

            // 如果当前已经是目标场景，则直接返回
            if (EditorSceneManager.GetActiveScene().path == scenePath)
            {
                Debug.Log($"Scene '{sceneName}' is already open.");
                return;
            }

            // 检查当前场景是否有未保存的更改
            if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
            { 
                // 打开新场景
                EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);
                Debug.Log($"Scene '{sceneName}' opened successfully.");
                
               
            }
        }
        
        private static string FindScenePath(string sceneName)
        {
            string[] guids = AssetDatabase.FindAssets($"t:Scene {sceneName}");
            foreach (string guid in guids)
            {
                string path = AssetDatabase.GUIDToAssetPath(guid);
                if (Path.GetFileNameWithoutExtension(path) == sceneName)
                {
                    return path;
                }
            }
            return null;
        }
        
    }
}
